<template>
  <div class="live-layout">
    <div class="live-left">
      <div id="video-live" class="live-stream"></div>
    </div>
    <div class="live-right">
      <div class="live-panel"></div>
    </div>
    <!-- <a-row :gutter="8">
      <a-col :xl="20" :lg="24" :md="24" :sm="24" :xs="24">
        <a-card>
          
        </a-card>
      </a-col>

      <a-col :xl="4" :lg="24" :md="24" :sm="24" :xs="24">
        <a-card>
          <div class="live-panel"></div>
        </a-card>
      </a-col>
    </a-row> -->
  </div>
</template>

<script>
  import {
    videoProfiles,
    videoFits,
    videoModes
  } from '@/setting/agora-config'

  import {
    clientEvents,
    initStreamErrors,
    createAgoraClient,
    createStream
  } from '@/utils/agora'

  let app_id = 'c6ed210255a34214abf1d905bbcfbac4'

  export default {
    name: 'LessonLive',

    data () {
      return {
        readyOk: false, // 就绪状态

        userId: 0, // 用户 id
        isLecturer: false, // 当前用户是否是 讲师

        videoElement: 'video-live', // 主播视频流窗口 html --> div
        channelNo: 'xiami', // 直播房间号

        // agora
        agoraClient: {}, // AgoraRTC 客户端
        localStream: {}, // 本地音/视频流

        streams: [] // 音视频流列表
      }
    },

    watch: {},

    created () {
      // 路由参数
      let obj = this.$route.params
      console.info(obj)
      //  获取 声网 key

      //  获取频道信息

      // let temUserId = Math.floor(Math.random() * 10 + 8)
      let temUserId = 10
      this.userId = temUserId
      console.log('userId', this.userId)

      if (this.userId === 10) {
        this.isLecturer = true
      }

      console.log('userId', this.userId)
      console.log('isLecturer', this.isLecturer)

      /* --------------------------------- 声网 client 初始化 ----------------------------------- */
      {
        this.agoraClient = createAgoraClient(null)

        let client = this.agoraClient
        client.init(app_id, () => {
            console.log('声网 -->客户端初始化成功')

            this.subscribeStreamEvents()

            client.join(null, this.channelNo, this.userId,
              uid => {
                // 加入成功回调
                console.log('client --> ' + uid + 'joined channel')

                if (this.isLecturer) {
                  let stream = createStream(this.userId, videoModes.video, videoProfiles['720p_30'])
                  this.localStream = stream

                  stream.init(() => {
                      client.publish(stream, err => {
                        console.log('视频流推送失败：' + err)
                      })

                      stream.play(this.videoElement)
                    },
                    err => {
                      console.log('设备初始化失败', err)
                      let error = initStreamErrors[err.msg]
                      // 设备初始化失败，开发阶段解决，线上也无法解决
                      console.log('设备初始化失败', error)
                    })
                }
                this.readyOk = true
              },
              err => {
                // 加入失败回调
                console.error('client join failed ', err)
              }
            )
          },
          err => {
            console.log('声网 -->客户端初始化失败', err)
          }
        )
      }
    },

    beforeMount () {

    },

    mounted () {

    },

    beforeUpdate () {
      this.streams.map((stream, index) => {
        stream.play(this.videoElement)
      })
    },

    beforeDestroy () {
      let client = this.agoraClient
      let stream = this.localStream

      if (stream) {
        client && client.unpublish(stream)
        stream && stream.close()
      }

      client && client.leave(() => {
          // to do something
          console.log('client succeed to leave')
        },
        () => {
          // to do something
          console.log('client failed to leave')
        }
      )
    },

    destroyed () {

    },

    methods: {
      /**
       * 退出直播
       *
       * @param e 事件
       */
      handleExit (e) {
        try {
          this.client && this.client.unpublish(this.localStream)
          this.localStream && this.localStream.close()
          this.client && this.client.leave(
            () => {
              console.log('Client succeed to leave.')
            },
            () => {
              console.log('Client failed to leave.')
            }
          )
        } finally {
          this.readyOk = false
          this.client = {}
          this.localStream = {}

          // redirect to index
          this.$router.push('/')
        }
      },

      /**
       * 发布视频流事件
       *    参考文档：https://docs.agora.io/cn/Voice/API%20Reference/web/interfaces/agorartc.client.html#subscribe
       *
       * @param agoraClient AgoraRTC Client
       */
      subscribeStreamEvents () {
        let client = this.agoraClient
        // 该回调通知 App 远程音视频流已添加

        client.on(clientEvents.streamAdded, evt => {
          let stream = evt.stream
          console.log('App 远程音视频流已添加：  ', evt)

          // 订阅远端视频流
          client.subscribe(stream, err => {
            // FIXME 订阅失败能怎么办呢？
            console.log('subscribe stream failed', err)
          })
        })

        client.on(clientEvents.peerLeave, evt => {
          let userId = evt.uid
          console.log(evt)
          console.log('peer has left: ' + userId)
          this.removeStream(evt.uid)
        })

        client.on(clientEvents.streamSubscribed, evt => {
          let remoteStream = evt.stream
          // let remoteUserId = remoteStream.getId()

          console.log('subscribe remote stream successfully：' + evt)

          remoteStream.play(this.videoElement, { fit: videoFits.contain })

          this.addStream(remoteStream)
        })

        client.on(clientEvents.streamRemoved, evt => {
          let stream = evt.stream
          console.log('stream removed: ' + evt)
          this.removeStream(stream.getId())
        })
      },

      // AgoraRTC  事件方法
      removeStream (userId) {
        this.streams.map((stream, index) => {
          if (stream.getId() === userId) {
            stream && stream.close()

            // let element = document.querySelector('#ag-item-' + userId)
            // if (element) {
            //   element.parentNode.removeChild(element)
            // }

            let tempList = [...this.streams]
            tempList.splice(index, 1)
            this.streams = tempList

            console.log('streams：' + this.streams)
          }
        })
      },

      addStream (stream, push = false) {
        let repetition = this.streams.some(item => {
          return item.getId() === stream.getId()
        })

        if (repetition) return

        if (push) {
          this.streams = this.streams.concat([stream])
        } else {
          this.streams = [stream].concat(this.streams)
        }
      }

    }
  }
</script>

<style lang="less" scoped>

  .live-layout {
    display: flex;
    height: 100%;
    border-radius: 4px;
    background-color: #192c3e;
    .live-left {
      flex: 1;
      .live-stream {
        height: 100%;
      }
    }
    .live-right {
      // flex: 1;
      width: 300px;
      .live-panel {
        height: 100%;
        border-radius: 4px;
        background-color: #30253e;
      }
    }
  }


</style>
